import { PrismaClient } from "@prisma/client"
import bc from "bcryptjs"
import randstr from "randomstring"

const p = new PrismaClient()

export default {
    async allProducts(req,res){
        let page = parseInt(req.query.page ?? 1)
        const search_str = req.query.search_str?? ""
        const per_page = parseInt(req.query.per_page ?? 10)
        const where = {
            OR: [
                {name:{contains:search_str}},
                {brand:{contains:search_str}},
                {spec:{contains:search_str}},
            ]
        }
        const total = await p.product.count({
            where
        })
        const page_count = Math.ceil(total/per_page)

        if(page<1){
            page=1
        }
        else if(page>page_count){
            page = page_count
        }
        let skip = (page-1)*per_page
        console.log(skip,per_page);
        
        const products = await p.product.findMany({
            where,
            skip,
            take: per_page
        })
        res.render("product-list",{products,page,page_count,per_page,search_str})
    },
    getProduct(req,res){
        res.send(req.params.id)
    },
    new_product_form(req,res){
        req.session.csrf_token = randstr.generate(40)
        const csrf_token = bc.hashSync(req.session.csrf_token)
        res.render("new-product",{csrf_token})
    },
    async add_product(req,res){
        //res.json(req.body)
        try{
            if(bc.compareSync(req.session.csrf_token,req.body.csrf_token)){
                delete req.body.csrf_token
                const product = await p.product.create({
                    data: req.body
                })
                res.redirect("/products")
            }
            else{
                res.send("Forbidden!!！")
            }
        }
        catch(e){
            res.send("Forbidden!!！")
        }
        

        
    }
}


